package com.dkts.oil.postgis;

import com.dkts.oil.mysql.entity.AisPoint;
import com.dkts.oil.mysql.entity.ShipInfo;
import org.springframework.beans.BeanUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ShipInfoBatchInsert {

    private static final String INSERT_SQL = """
        INSERT INTO ship_info (mmsi, imo, nationality, name, callsign, length, width, "left", tail, draught, uidkey,shiptype)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT (mmsi) DO NOTHING
    """;

    public static void batchInsert(List<ShipInfo> shipInfoList) {
        try (Connection conn = PostgresConnectionUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(INSERT_SQL)) {

            conn.setAutoCommit(false);  // 开启事务

            for (ShipInfo ship : shipInfoList) {
                ps.setObject(1, ship.getMmsi());
                ps.setObject(2, ship.getImo());
                ps.setString(3, ship.getNationality());
                ps.setString(4, ship.getName());
                ps.setString(5, ship.getCallsign());
                ps.setObject(6, ship.getLength());
                ps.setObject(7, ship.getWidth());
                ps.setObject(8, ship.getLeft());
                ps.setObject(9, ship.getTail());
                ps.setObject(10, ship.getDraught());
                ps.setString(11, ship.getUidkey());
                ps.setObject(12, ship.getShiptype());
                ps.addBatch();
            }

            ps.executeBatch();
            conn.commit();
            System.out.println("批量插入成功");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void insertShipInfo(Map<String, List<AisPoint>> aisPointsByMmsi,String uuid){
        List<ShipInfo> shipInfoList=new ArrayList<>();
        for (Map.Entry<String, List<AisPoint>> entry : aisPointsByMmsi.entrySet()) {
            List<AisPoint> points = entry.getValue();
            if(points.size()>0){
                ShipInfo shipInfo=new ShipInfo();
                AisPoint aisPoint=points.get(0);
                BeanUtils.copyProperties(aisPoint, shipInfo);
                shipInfo.setUidkey(uuid);
                shipInfoList.add(shipInfo);
            }
        }
        try {
            batchInsert(shipInfoList);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
